package com.yanxu.oauth2.server.config;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-09-24-2025
 * @Description: security 配置类
 */
@Configuration  // 标志成为一个配置类
@EnableWebSecurity  // 开启 security 的配置
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    // 注入 redis 连接工厂， RedisConnectionFactory
    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 初始化 RedisTokenStore 用于将token 存储到redis
     * @return
     */
    @Bean
    public RedisTokenStore redisTokenStore() {
        // 创建 RedisTokenStore 对象
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        //设置 key的层级前缀，方便查询
        redisTokenStore.setPrefix("TOKEN:");
        return redisTokenStore;
    }

    /**
     * 初始化密码编码器，使用 MD5 加密密码
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            /**
             * 加密
             * @param rawPassword  原始密码
             * @return
             */
            @Override
            public String encode(CharSequence rawPassword) {
                return DigestUtil.md5Hex(rawPassword.toString());
            }

            /**
             * 校验
             * @param rawPassword  原始密码
             * @param encodedPassword  加密密码
             * @return
             */
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return DigestUtil.md5Hex(rawPassword.toString()).equals(encodedPassword);
            }
        };
    }


    /**
     * 初始化认证管理器
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * 定义放行和认证规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //csrf 关闭
        http.csrf().disable()
                .authorizeRequests()
                 // /oauth/**  、/actuator/** 这两个端点下的直接放行
                .antMatchers("/oauth/**","/actuator/**").permitAll()
                .and()
                .authorizeRequests()
                //其他的请求，都需要进行认证
                .anyRequest().authenticated();
    }
}